package cn.trip.biz.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripOrderInfoVO;
import cn.itrip.beans.vo.ItripOrderSelect;
import cn.itrip.beans.vo.ItripPersonalOrderRoomVO;
import cn.itrip.common.Page;
import cn.itrip.common.TokenUtil;
import cn.trip.biz.service.ItripHotelOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Map;

@Api(value = "Order|订单查询")
@Controller
@RequestMapping("/api/hotelorder")
public class ItripOrderController {
    @Resource(name = "itripHotelOrderService")
    private ItripHotelOrderService itripHotelOrderService;
    @Autowired
    private TokenUtil tokenUtil;

    /**
     * （多条件）查询订单列表
     *
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "/getpersonalorderlist", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "查看某当前用户的所有订单||根据条件查看某用户的订单", produces = "application/json",
            notes = "根据条件查询个人订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "itripOrderSelect", value = "订单筛选信息")
    })
    public Dto<Page> orderListByCondition(@RequestBody ItripOrderSelect itripOrderSelect,
                                          HttpServletRequest request) throws ParseException, SolrServerException {
        Dto<Page> dto = null;
        String token = request.getHeader("token");

        if (tokenUtil.isExist(token)) {
            //从redis里面拿userId
            ItripUser user = itripHotelOrderService.user(token);
            if (user != null) {
                itripOrderSelect.setUserId(user.getId());
                if (itripOrderSelect.getPageNo() == 0) {
                    itripOrderSelect.setPageNo((itripOrderSelect.getPageNo()) * itripOrderSelect.getPageSize());
                } else {
                    itripOrderSelect.setPageNo((itripOrderSelect.getPageNo() - 1) * itripOrderSelect.getPageSize());
                }

                dto = itripHotelOrderService.selectByUserId(itripOrderSelect);
            } else {
                dto = new Dto();
                dto.setSuccess("false");
                dto.setMsg("登陆已过期，请重新登陆！");
            }
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("当前用户没有登陆，请先登录再操作");
        }
        return dto;
    }

    /**
     * 查看订单详情
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getpersonalorderinfo/{id}", method = RequestMethod.GET, headers = "token")
    @ApiOperation(value = "查看某用户订单列表中的某一条订单的详情", produces = "application/json", notes = "根据订单id查询订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "订单id", required = true),
    })
    public Dto<ItripHotelOrder> orderDetail(HttpServletRequest request, @PathVariable String id) {
        String token = request.getHeader("token");
        Dto dto = null;
        if (tokenUtil.isExist(token)) {
            ItripUser user = itripHotelOrderService.user(token);
            String redisOrderKey = "order:userId=" + user.getId();
            dto = itripHotelOrderService.selectDetailByidFromRedis(new Long(id), redisOrderKey);
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("当前用户没有登陆，请先登录再操作");
        }
        return dto;
    }


    /**
     * 查看房间详情
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getpersonalorderroominfo/{id}", method = RequestMethod.GET, headers = "token")
    @ApiOperation(value = "查看某用户订单列表中的某一条订单的详情", produces = "application/json", notes = "根据订单id查询订单详情")
    @ApiImplicitParam(paramType = "query", name = "id", value = "订单id", required = true)
    public Dto<ItripHotelOrder> roomDetail(HttpServletRequest request, @PathVariable String id) {
        String token = request.getHeader("token");
        Dto dto = null;
        if (tokenUtil.isExist(token)) {
            dto = itripHotelOrderService.getItripHotelOrderRoomInfoById(Long.valueOf(id));
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("当前用户没有登陆，请先登录再操作");
        }
        return dto;
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteOrder", method = RequestMethod.POST, headers = "token")
    @ApiImplicitParam(paramType = "query", name = "orderId", value = "订单id", required = true)
    public Dto deleteOrder(@RequestParam(value = "orderId") String orderId,
                           HttpServletRequest request) {
        String token = request.getHeader("token");
        Dto dto = null;
        if (tokenUtil.isExist(token)) {
            dto = itripHotelOrderService.deleteByPrimaryKey(new Long(orderId));
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("当前用户没有登陆，请先登录再操作");
        }
        return dto;
    }

    @ApiOperation(value = "生成订单", httpMethod = "POST")
    @RequestMapping(value = "/addhotelorder", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto addHotelOrder(@RequestBody Map<String, Object> HotelOrderMap, HttpServletRequest request) {
        String token = request.getHeader("token");
        Dto dto = null;
        if (tokenUtil.isExist(token)) {
            dto = itripHotelOrderService.addHotelOrder(HotelOrderMap, token);
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("当前用户没有登陆，请先登录再操作");
        }
        return dto;
    }


    @ResponseBody
    @RequestMapping(value = "/getpreorderinfo", method = RequestMethod.POST, headers = "token")
    @ApiImplicitParam(paramType = "query", name = "orderId", value = "订单id", required = true)
    public Dto getOrderInfo(@RequestBody ItripOrderInfoVO itripOrderInfoVO,
                            HttpServletRequest request) {
        String token = request.getHeader("token");
        Dto dto = null;
        if (tokenUtil.isExist(token)) {
            dto = itripHotelOrderService.getOrderInfo(itripOrderInfoVO, token);
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("当前用户没有登陆，请先登录再操作");
        }
        return dto;
    }

    /***
     * 10分钟一次 针对未支付订单，如果当前时间-创建时间>10=分钟，状态变为已取消
     */
    @Scheduled(cron = "0 0/10 * * * * ")
    public void updateStatusUnpayToCancel() {
        try {
            System.out.println("开始执行0-1的任务");
            boolean flag = itripHotelOrderService.updateStatusByScheduled(1);
            System.out.println("执行结束0-1" + flag);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 半小时一次 针对支付成功，如果当前时间>退房时间，状态变为已消费
     */
    @Scheduled(cron = "0 0/30 * * * * ")
    public void updateStatusSuccessToConsumption() {
        try {
            System.out.println("开始执行2-3的任务");
            boolean flag = itripHotelOrderService.updateStatusByScheduled(2);
            System.out.println("执行结束2-3" + flag);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0 0 0 * * * ")
    public void insertTempByScheduled() {
        try {
            System.out.println("开始执行新增的任务");
            boolean flag = itripHotelOrderService.insertTempByScheduled();
            System.out.println("执行结束新增" + flag);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
